import { uuidGenerator } from './common'

interface IWorker {
  workerId: string
  workerInstance: Worker
}

export class WorkerFactory {
  private taskFn: () => void
  protected workers: IWorker[]

  constructor(taskFn: () => void) {
    this.taskFn = taskFn
    this.workers = []
  }

  create(): { workerId: string, instance: WorkerFactory } {
    const workerId = uuidGenerator()
    const taskFn = this.taskFn
    const workerInstance = new Worker(URL.createObjectURL(new Blob([`(${taskFn.toString()})()`], { type: 'text/javascript' })))
    this.workers.push({
      workerId,
      workerInstance,
    })

    return {
      instance: this,
      workerId,
    }
  }

  send(workerId: string, params: any, cb: (data: any) => void) {
    const worker = this.workers.find(worker => worker.workerId === workerId)
    if (!worker) {
      console.warn(`workerId不存在: ${workerId}`)
      return
    }

    worker.workerInstance.postMessage(params)
    worker.workerInstance.onmessage = (e: any) => {
      cb(e.data)
    }
  }
}
